<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $withCount = ['goods'];

    protected $fillable = [
    	'name',
    	'icon',
    	'sort',
    	'pid'
    ];

    public function goods()
    {
        return $this->hasMany(Goods::class, 'category_id');
    }

    public function scopeTop($query)
    {
    	return $query->where('pid', 0);
    }

    public function getIconImageAttribute()
    {
    	return \Storage::url($this->icon);
    }

    public function subcates()
    {
        return $this->hasMany(Category::class, 'pid');
    }

    public function parentCate()
    {
        return $this->belongsTo(Category::class, 'pid')->withDefault();
    }

    public function addSub($data)
    {
        $this->subcates()->saveMany($data);
    }

    public function topGoods()
    {
        //$ids = $this->subcates->pluck('id');
        return $this->hasManyThrough('App\Models\Goods', 'App\Models\Category', 'pid', 'category_id')->limit(10);
    }

    public function subcates_goods() {
        return $this->hasManyThrough('App\Models\Goods', 'App\Models\Category', 'pid', 'category_id');
    }

    public function getGoods()
    {
        if($this->subcates()->exists())
        {
            return $this->subcates_goods()->paginate();
        }
        return $this->goods()->paginate();
    }

    public function setPidAttribute($v) {
        $this->attributes['pid'] = intval($v);
    }

    public static function boot() {
        parent::boot();
        static::deleted(function($model) {
            $model->goods()->update(['category_id' => 0]);
        });
    }

    public function getGoodsTotalCountAttribute() {
        return $this->subcates->sum('goods_count');
    }
}
